import sys

import pygame

from klocek import Klocek
from plansza import Plansza
from functions import printSurface

class Game:
    def __init__(self):
        pygame.init()

        pygame.display.set_caption("Tetris")
        self.okienko = pygame.display.set_mode((500,500))

        self.clock = pygame.time.Clock()
        self.bg = pygame.image.load("data/tlo.png").convert()
        self.klocki = [Klocek(), Klocek()]
        self.klocki[0].start()
        self.plansza = Plansza()
        self.pause = False
        self.score = 0
        self.level = 1
        
        self.loop()

    def drawInfo(self, dest):
        printSurface(dest, str(self.score), 25, (0,0,0), (417, 97), 1)
        printSurface(dest, str(self.level), 25, (0,0,0), (417, 200), 1)

    def events(self):
        evl = pygame.event.get()
        for ev in evl:
            if ev.type == pygame.MOUSEBUTTONDOWN:
                pause = pygame.Rect(350,385,140,30)
                menu = pygame.Rect(350,415,140,30)
                koniec = pygame.Rect(350,445,140,30)
                if pause.collidepoint(ev.pos):
                    self.pause = not self.pause
                elif menu.collidepoint(ev.pos):
                    print "menu"
                elif koniec.collidepoint(ev.pos):
                    self.exit()
            elif ev.type == pygame.KEYDOWN:
                if ev.key == pygame.K_LEFT:
                    if self.klocki[-2].pos[0] > 27:
                        self.klocki[-2].pos[0] -= 20
                elif ev.key == pygame.K_RIGHT:
                    if self.klocki[-2].image.get_rect(x=self.klocki[-2].pos[0]).right < 270:
                        self.klocki[-2].pos[0] += 20
                elif ev.key == pygame.K_UP:
                    self.klocki[-2].rotate()
                elif ev.key == pygame.K_DOWN:
                    self.klocki[-2].fall()

    def exit(self):
        sys.exit()

    def loop(self):
        while 1:
            self.events()
            new = True
            for item in self.klocki:
                if item.state == "f":
                    new = False

            if new:
                self.klocki[-1].start()
                self.klocki.append(Klocek())

            if not self.pause:
                for item in self.klocki:
                    if item.update() == True:
                        self.plansza.add(self.klocki.pop(0))

            self.okienko.blit(self.bg, (0,0))

            for item in self.klocki:
                item.draw(self.okienko)

            self.drawInfo(self.okienko)
            self.plansza.draw(self.okienko)
            pygame.display.flip()
            self.clock.tick(50)
Game()
